//******************************************************************************
//this code is protected by the GNU affero GPLv3
//author:Sylvain BERTRAND <sylvain.bertrand AT gmail dot com>
//                        <digital.ragnarok AT gmail dot com>
//******************************************************************************
#include "globals.h"

static s8 get_registry(struct client *c,struct msg *m)
{
  if(m->req_dws<3){
    PERR("client(%d):fatal:display::get_registry request misses registry_id\n",
                                                                         c->so);
    return LWL_ERR;
  }

  LOG_WIRE("client(%d):display::get_registry registry_id=%u\n",c->so,m->req[2]);

  return display_get_registry(c,m->req[2]);
}

static s8 sync(struct client *c,struct msg *m)
{
  if(m->req_dws<3){
    PERR("client(%d):fatal:display::sync request misses callback_id\n",c->so);
    return LWL_ERR;
  }

  LOG_WIRE("client(%d):display::sync callback_id=%u\n",c->so,m->req[2]);

  return display_sync(c,m->req[2]);
}

s8 wl_display_req(struct client *c,struct msg *m)
{
  s8 r;
  switch(m->req_op){
  case WL_DISPLAY_GET_REGISTRY:
    r=get_registry(c,m);
    break;
  case WL_DISPLAY_SYNC:
    r=sync(c,m);
    break;
  default:
    PERR("client(%d):fatal:display:request unknown opcode %u\n",c->so,
                                                                     m->req_op);
    r=LWL_ERR;
  }
  return r;
}

#define EV_DELETE_ID_DWS 3
s8 wl_display_ev_delete_id(struct client *c,u32 id)
{
  u32 ev[EV_DELETE_ID_DWS];

  ev[0]=WL_DISPLAY_ID;
  u16 ev_sz=EV_DELETE_ID_DWS*sizeof(u32);
  ev[1]=ev_sz<<16|WL_DISPLAY_DELETE_ID;
  ev[2]=id;

  struct io_vec iov;
  iov.base=&ev;
  iov.len=ev_sz;

  struct msg_hdr msg;
  memset(&msg,0,sizeof(msg));
  msg.iov=&iov;
  msg.iov_len=1;

  LOG_WIRE("client(%d):display::delete_id id=%u\n",c->so,id);

  l r;
  while(1){r=sendmsg(c->so,&msg,0); if(r!=-EINTR) break;}

  if(ISERR(r)){
    PERR("client(%d):fatal(%ld):display::delete_id unable to send event\n",
                                                                       c->so,r);
    return LWL_ERR;
  }

  if(r!=ev_sz){
    PERR("client(%d):fatal:display::delete_id event only %ld/%ld were sent\n",
                                                                 c->so,r,ev_sz);
    return LWL_ERR;
  }
  return LWL_OK; 
}
